﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SOWY.common;
using System.Data.Odbc;
using System.Data;

namespace SOWY
{
    class LogOperation
    {
        private string DATABASE_CONN_STRING;

        public LogOperation()
        {
            initiateLogFile();
        }

        #region Logging
        private void initiateLogFile()
        {
            if (!File.Exists(GeneralConstant.DATABASE_FOLDER + GeneralConstant.DATABASE_CSV_LOG_FILE))
            {
                using (FileStream fs = File.Create(GeneralConstant.DATABASE_FOLDER + GeneralConstant.DATABASE_CSV_LOG_FILE, 1024))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes("action,startDate,endDate,task\n");
                    fs.Write(info, 0, info.Length);
                    fs.Close();
                }
            }
            DATABASE_CONN_STRING = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + GeneralConstant.DATABASE_FOLDER + ";Extensions=asc,csv,tab,txt;";
        }

        public void insertLog(string action, string task, string startDate, string endDate)
        {
            string filePath = GeneralConstant.DATABASE_FOLDER + GeneralConstant.DATABASE_CSV_LOG_FILE;
            using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.WriteLine("\"" + action + "\",\"" + startDate + "\",\"" + endDate + "\",\"" + task + "\"");
                sw.Close();
            }
        }
        public DataTable readLog()
        {
            OdbcConnection conn = new OdbcConnection(DATABASE_CONN_STRING);
            conn.Open();
            OdbcDataAdapter dataAdapter = new OdbcDataAdapter("SELECT * FROM [" + GeneralConstant.DATABASE_CSV_LOG_FILE + "]", conn);
            DataTable dt = new DataTable();
            dataAdapter.Fill(dt);
            dataAdapter.Dispose();
            conn.Close();
            return dt;
        }
        public void deleteLog()
        {
            string filePath = GeneralConstant.DATABASE_FOLDER + GeneralConstant.DATABASE_CSV_LOG_FILE;
            List<string> lines = File.ReadAllLines(filePath).ToList();
            File.WriteAllLines(filePath, lines.GetRange(0, lines.Count - 1));
        }
        #endregion

        #region Existance checker
        private bool isFolderExist(string path)
        {
            if (Directory.Exists(path))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool isFileExist(string location)
        {
            if (File.Exists(location))
            {
                return true;
            }
            return false;
        }
        #endregion
    }
}
